<?php
/**
 * @file
 */

/**
 * Form builder; the edit word form.
 */
function wordgame_word_edit($form, &$form_state, $word = NULL) {
  global $user;
  $form['#attributes']['class'][] = 'wordgame-word-edit-form';

  if (!$word) {
    $word = new StdClass();
    $word->modified = REQUEST_TIME;
    $word->status = 1;
    $word->word = '';
    $word->dict = 'en_vi';
  }

  $form['#word'] = $word;

  // Start with the default user account fields.
  // Account information.
  $form['word'] = array(
    '#type'   => 'container',
    '#weight' => -10,
  );
  // Only show name field on registration form or user can change own username.
  $form['word']['word'] = array(
    '#type' => 'textfield',
    '#title' => t('Word'),
    '#maxlength' => 255,
    '#required' => TRUE,
    '#attributes' => array('class' => array('wordgame-word-word')),
    '#default_value' => !empty($word->word) ? $word->word : '',
    '#weight' => -10,
  );

  $form['client']['status'] = array(
    '#type' => 'checkbox',
    '#title' => t('Active'),
    '#default_value' => !empty($word->status) ? $word->status : '',
    '#attributes' => array('class' => array('wordgame-word-status')),
  );

  // Attach field widgets, and hide the ones where the 'user_register_form'
  // setting is not on.
  $langcode = entity_language('wordgame_word', $form['#word']);
  field_attach_form('wordgame_word', $form['#word'], $form, $form_state, $langcode);

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  $form['#validate'][] = 'wordgame_word_edit_validate';
  // Add the final user registration form submit handler.
  $form['#submit'][] = 'wordgame_word_edit_submit';


  return $form;
}

/**
 * Validation function for the client form.
 */
function wordgame_word_edit_validate($form, &$form_state) {
  entity_form_field_validate('wordgame_word', $form, $form_state);
}

/**
 * Submit handler for the client form.
 */
function wordgame_word_edit_submit($form, &$form_state) {
  // Remove unneeded values.
  form_state_values_clean($form_state);

  $word = $form['#word'];

  entity_form_submit_build_entity('wordgame_word', $word, $form, $form_state);

  // Populate $edit with the properties of $account, which have been edited on
  // this form by taking over all values, which appear in the form values too.
  $edit = array_intersect_key((array) $word, $form_state['values']);
  $word = wordgame_word_save($word);

  $form_state['word'] = $word;
  drupal_set_message(t('The word has been saved successful'));
  drupal_goto('admin/wordgame/words');

}
